<template>
  <div class="page-new-distribution-prod">
    <div class="new-page-title">
      <div class="line" />
      <div class="text">
        {{
          !dataForm.distributionProdId
            ? $t('marketing.newDisProducts')
            : $t('marketing.modifyDisnProducts')
        }}
      </div>
    </div>
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      class="form-box"
      label-width="auto"
      @submit.prevent
      @keyup.enter="dataFormSubmit()"
    >
      <el-form-item
        :label="$t('groups.relatedProducts') + ':'"
        :required="true"
      >
        <div v-if="prodData[0] != null">
          <el-card
            :body-style="{ padding: '0px' }"
            style="height: 160px; width: 120px"
          >
            <prod-pic
              height="104px"
              width="100%"
              :pic="prodData[0].pic"
            />
            <div class="card-prod-bottom">
              <span
                style="width: 79px;"
                class="card-prod-name"
              >{{ prodData[0].prodName }}</span>
              <div
                class="default-btn text-btn"
                @click="deleteRelation"
              >
                {{ $t("text.delBtn") }}
              </div>
            </div>
          </el-card>
        </div>
        <div
          v-else
          class="default-btn"
          @click="addProd"
        >
          {{
            $t("product.select")
          }}
        </div>
      </el-form-item>

      <div v-if="dataForm.defaultReward === 0">
        <el-form-item
          :label="$t('marketing.rewardRatio') + ':'"
          prop="awardType"
        >
          <el-radio-group v-model="dataForm.awardProportion">
            <el-radio :label="0">
              {{ $t("marketing.proporteward") }}
            </el-radio>
            <el-radio :label="1">
              {{ $t("marketing.rewardByFixedValue") }}
              <el-tooltip
                class="item"
                effect="light"
                placement="top"
              >
                <template #content>
                  <div>
                    {{ $t("marketing.tips") }}
                  </div>
                </template>
                <span>
                  <el-icon><QuestionFilled /></el-icon>
                </span>
              </el-tooltip>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="$t('marketing.inviterReward') + ':'"
          prop="awardType"
        >
          <el-radio-group v-model="dataForm.parentAwardSet">
            <el-radio :label="0">
              {{ $t("station.close") }}
            </el-radio>
            <el-radio :label="1">
              {{ $t("groups.turnOn") }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          :label="(dataForm.awardNumberSet === 1 ? $t('marketing.amountSetting') : $t('marketing.rewardAmount')) + ':'"
          :required="true"
        >
          <div v-if="dataForm.awardNumberSet === 0">
            <el-input
              v-model="dataForm.awardNumbers"
              type="number"
              :precision="2"
              :min="0"
              style="width: 200px"
              @blur="() => { dataForm.awardNumbers = dataForm.awardNumbers * 1 }"
            >
              <template #append>
                <span v-if="dataForm.awardProportion === 1">{{
                  $t("admin.dollar")
                }}</span>
                <span v-else>%</span>
              </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item
          v-if="dataForm.awardNumberSet === 0 && dataForm.parentAwardSet === 1"
          :label="$t('marketing.inviterRewardAmount') + ':'"
        >
          <el-input
            v-if="dataForm.parentAwardSet === 1"
            v-model="dataForm.parentAwardNumbers"
            :precision="2"
            :min="0"
            style="width: 200px"
          >
            <template #append>
              <span v-if="dataForm.awardProportion === 1">{{
                $t("admin.dollar")
              }}</span>
              <span v-else>%</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          v-if="dataForm.state < 2"
          :label="$t('product.status') + ':'"
          prop="state"
        >
          <el-radio-group v-model="dataForm.state">
            <el-radio :label="1">
              {{ $t("publics.UpperShelf") }}
            </el-radio>
            <el-radio :label="0">
              {{ $t("publics.LowerShelf") }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <el-form-item style="margin-top: 20px">
        <div
          class="default-btn"
          @click="back()"
        >
          {{
            $t("shopFeature.edit.back")
          }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="dataFormSubmit()"
        >
          {{
            $t("crud.filter.submitBtn")
          }}
        </div>
      </el-form-item>
    </el-form>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addProdVisible"
      ref="addProdRef"
      :is-distribution="true"
      @refresh-discount-prods="selectDiscountProds"
    />
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import AddOrUpdate from './components/add-or-update.vue'

const Data = reactive({
  dataForm: {
    prodId: 0,
    distributionAmount: 0,
    awardId: 0,
    state: 1,
    defaultReward: 0,
    awardProportion: 0,
    awardNumberSet: 0,
    awardNumbers: '',
    parentAwardNumbers: '',
    parentAwardSet: 0
  },
  levelData: [],
  prodData: [],
  isSubmit: false,
  addProdVisible: false,
  isInviterReward: true,
  dataRule: {

  }
})
const { dataForm, prodData, addProdVisible, dataRule } = toRefs(Data)

const commonStore = useCommonStore()
onMounted(() => {
  const flag = sessionStorage.getItem('bbcDistributionProdData') !== 'undefined'
  const data = flag ? JSON.parse(sessionStorage.getItem('bbcDistributionProdData')) : null
  init(data)
  const title = !Data.dataForm.distributionProdId ? $t('marketing.newDisProducts') : $t('marketing.modifyDisnProducts')
  commonStore.replaceSelectMenu(title)
})

const dataFormRef = ref()
const init = (data) => {
  Data.isSubmit = false
  Data.dataForm.distributionProdId = 0
  if (data) {
    Data.dataForm = data
    Data.prodData[0] = Data.dataForm.product
  } else {
    dataFormRef.value.resetFields()
    Data.dataForm.defaultReward = 0
    Data.dataForm.awardProportion = 0
    Data.dataForm.awardNumberSet = 0
    Data.dataForm.parentAwardSet = 0
    Data.dataForm.awardNumbers = 1
    Data.dataForm.parentAwardNumbers = 1
    Data.dataForm.state = 1
    Data.levelData = []
    Data.prodData = []
  }
  sessionStorage.setItem('bbcDistributionProdData', undefined)
}

// 删除关联商品数据
const deleteRelation = () => {
  Data.dataForm.prodId = null
  Data.prodData = []
}

const addProdRef = ref()
// 打开选择商品
const addProd = () => {
  Data.addProdVisible = true
  nextTick(() => {
    addProdRef.value.init(0, Data.prodData)
  })
}

// 商品选择回调
const selectDiscountProds = (prods) => {
  if (prods) {
    nextTick(() => {
      http({
        url: http.adornUrl('/distribution/distributionProd/count'),
        method: 'get',
        params: http.adornParams({
          prodId: prods[0].prodId
        })
      }).then(() => {
        Data.dataForm.prodId = prods[0].prodId
        Data.prodData[0] = prods[0]
      })
    })
  }
}

const checkAwardNumberSet = () => {
  if (Data.dataForm.awardNumberSet === 0) {
    if (checkAwardNumbers(Data.dataForm.awardNumbers) ||
      (Data.dataForm.parentAwardSet === 1 && checkAwardNumbers(Data.dataForm.parentAwardNumbers))) {
      return true
    }
  }
  if (Data.dataForm.awardNumberSet === 1) {
    for (let i = 0; i < Data.levelData.length; i++) {
      const level = Data.levelData[i]
      if (checkAwardNumbers(level.awardNumber) || (Data.dataForm.parentAwardSet === 1 && checkAwardNumbers(level.parentAwardNumber))) {
        return true
      }
    }
  }
  return false
}

// 表单提交
const dataFormSubmit = () => {
  if (Data.dataForm.defaultReward === 0 && checkAwardNumberSet()) {
    return
  }
  if (Data.dataForm.awardNumberSet === 0 && Data.dataForm.parentAwardSet === 1) {
    if (parseFloat(Data.dataForm.parentAwardNumbers) <= 0) {
      ElMessage.error($t('marketing.valueSetting'))
      return
    }
  }

  if (Data.prodData[0] == null) {
    ElMessage.error($t('marketing.pleaseSelectAProduct'))
    return
  }
  dataFormRef.value.validate((valid) => {
    if (valid) {
      if (Data.dataForm.awardNumberSet === 1) {
        // 创建json存入奖励表
        const awardNumberjson = []
        const parentAwardNumberjson = []
        Data.levelData.forEach((item) => {
          awardNumberjson.push(Number.parseFloat(item.awardNumber).toFixed(2))
          parentAwardNumberjson.push(Number.parseFloat(item.parentAwardNumber).toFixed(2))
        })
        Data.dataForm.awardNumbers = JSON.stringify(awardNumberjson)
        Data.dataForm.parentAwardNumbers = JSON.stringify(parentAwardNumberjson)
      }
      const param = Data.dataForm
      if (Data.isSubmit) {
        return false
      }
      Data.isSubmit = true
      http({
        url: http.adornUrl('/distribution/distributionProd'),
        method: param.distributionProdId ? 'put' : 'post',
        data: http.adornData(param)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            back()
          }
        })
      }).catch((e) => {
        Data.isSubmit = false
      })
    }
  })
}

const checkAwardNumbers = (number) => {
  if (!number && number !== 0) {
    ElMessage.error($t('marketing.valueSetBeEmpty'))
    return true
  }
  const regex = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
  if (!regex.test(number)) {
    ElMessage.error($t('marketing.valueSetting'))
    return true
  }
  if (Data.dataForm.parentAwardSet && !Data.dataForm.awardProportion) {
    if (parseFloat(Data.dataForm.parentAwardNumbers) + parseFloat(Data.dataForm.awardNumbers) >= 100) {
      ElMessage.error($t('marketing.rewardAmount') + '+' + $t('marketing.inviterRewardAmount') + $t('marketing.totalAwardOverTips'))
      return true
    }
    if (parseFloat(Data.dataForm.awardNumbers) > 100) {
      ElMessage.error($t('marketing.rewardRatio') + $t('marketing.totalAwardOverTips'))
      return true
    }
  }
}

const router = useRouter()
const back = () => {
  router.push({
    path: '/marketing/distribution-prod/index'
  })
}
</script>

<!-- eslint-disable vue-scoped-css/enforce-style-type -->
<style lang="scss">
.page-new-distribution-prod {
  .el-input__inner {
    padding: 2px;
    border-radius: 3px;
  }

  .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 20px;
  }

  .award-box {
    input {
      border-top-right-radius: 0px;
      border-bottom-right-radius: 0px;
    }

    .el-input-group__append,
    .el-input-group__prepend {
      padding: 0 10px;
    }
  }

  .level-table-box {
    background: #fff;
    border: 1px solid #eee;
    border-radius: 10px;
    margin-top: 10px;
    padding: 5px;
  }

  .elTable th {
    padding: 10px 0 !important;
  }

  .elTable td {
    padding: 2px 0 !important;
  }

  .table-input-box {
    margin-top: 300px;
    width: 300px;
  }

  .table-template {
    text-align: left;
  }

  .table-template>* {
    display: inline-block;
    margin: auto;
  }

  .card-prod-container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
  }

  .form-box {
    margin-left: 40px;
  }
}

.page-new-distribution-prod :deep(.el-form-item--mini.el-form-item),
.page-new-distribution-prod :deep(.el-form-item--small.el-form-item) {
  margin-bottom: 20px;
}

div :deep(.el-input-group__prepend) {
  padding: 0 12px;
}
</style>
